<template>
  <div class="appointment-management">
    <div class="page-header">
      <h2>面试预约管理</h2>
      <div class="header-actions">
        <el-button type="primary" :disabled="multiple" @click="handleBatchConfirm">
          <i class="el-icon-finished"></i> 批量确认
        </el-button>
        <el-button type="warning" @click="loadReminders">
          <i class="el-icon-bell"></i> 待提醒
        </el-button>
      </div>
    </div>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="学生ID" prop="studentId">
        <el-input v-model="queryParams.studentId" placeholder="请输入学生ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="时段ID" prop="slotId">
        <el-input v-model="queryParams.slotId" placeholder="请输入时段ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待面试" value="0" />
          <el-option label="进行中" value="1" />
          <el-option label="已完成" value="2" />
          <el-option label="已取消" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="预约ID" align="center" prop="appointmentId" />
      <el-table-column label="申请ID" align="center" prop="applicationId" />
      <el-table-column label="学生ID" align="center" prop="userId" />
      <el-table-column label="时段ID" align="center" prop="slotId" />
      <el-table-column label="面试类型" align="center" prop="interviewType">
        <template #default="{ row }">
          <el-tag :type="row.interviewType === '1' ? 'success' : 'info'">{{ row.interviewType === '1' ? '线下' : '线上' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? 'info' : (row.status === '1' ? 'warning' : (row.status === '2' ? 'success' : 'danger'))">
            {{ row.status === '0' ? '待面试' : (row.status === '1' ? '进行中' : (row.status === '2' ? '已完成' : '已取消')) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="{ row }">
          <span>{{ parseTime(row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="{ row }">
          <el-button size="small" type="text" icon="el-icon-finished" @click="handleConfirm(row)">确认</el-button>
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleComplete(row)">记录结果</el-button>
          <el-button size="small" type="text" icon="el-icon-message" @click="handleRemind(row)">提醒</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 完成面试并记录结果 -->
    <el-dialog title="记录面试结果" :visible.sync="completeOpen" width="600px" append-to-body>
      <el-form ref="completeFormRef" :model="completeForm" :rules="completeRules" label-width="120px">
        <el-form-item label="面试评分" prop="interviewScore">
          <el-input-number v-model="completeForm.interviewScore" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="面试结果" prop="interviewResult">
          <el-radio-group v-model="completeForm.interviewResult">
            <el-radio label="2">通过</el-radio>
            <el-radio label="3">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="反馈意见" prop="interviewFeedback">
          <el-input type="textarea" v-model="completeForm.interviewFeedback" :rows="4" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitComplete">确 定</el-button>
        <el-button @click="completeOpen=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAppointmentsByClub,
  confirmAppointment,
  batchConfirmAppointments,
  completeInterview,
  getAppointmentsForReminder,
  sendAppointmentReminder,
  getMyClubContext
} from '@/api/campus/club'

export default {
  name: 'InterviewAppointmentManagement',
  dicts: ['appointment_status'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      appointmentList: [],
      completeOpen: false,
      currentAppointmentId: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        slotId: null,
        status: null
      },
      completeForm: {
        interviewScore: null,
        interviewResult: '2',
        interviewFeedback: ''
      },
      completeRules: {
        interviewScore: [{ required: true, message: '请输入面试评分', trigger: 'blur' }],
        interviewResult: [{ required: true, message: '请选择面试结果', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.loading = true
      const ctx = await getMyClubContext()
      const clubId = ctx?.data?.clubId
      
      // 检查clubId是否有效，避免调用API时出现null值
      if (!clubId) {
        // 如果clubId为null或无效，使用空列表
        this.appointmentList = []
        this.total = 0
        this.loading = false
        return
      }
      
      getAppointmentsByClub(clubId).then(res => {
        this.appointmentList = res.data || []
        this.total = this.appointmentList.length
        this.loading = false
      }).catch(() => {
        // API调用失败时使用空列表
        this.appointmentList = []
        this.total = 0
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.appointmentId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleConfirm(row) {
      this.$modal.confirm('确认该预约？').then(() => confirmAppointment(row.appointmentId)).then(() => {
        this.$modal.msgSuccess('已确认')
        this.getList()
      }).catch(() => {})
    },
    handleBatchConfirm() {
      this.$modal.confirm('确认批量确认选中的预约？').then(() => {
        return batchConfirmAppointments({ appointmentIds: this.ids })
      }).then(() => {
        this.$modal.msgSuccess('批量确认成功')
        this.getList()
      }).catch(() => {})
    },
    handleComplete(row) {
      this.currentAppointmentId = row.appointmentId
      this.completeForm = { interviewScore: null, interviewResult: '2', interviewFeedback: '' }
      this.completeOpen = true
    },
    submitComplete() {
      this.$refs['completeFormRef'].validate(valid => {
        if (!valid) return
        const data = {
          appointmentId: this.currentAppointmentId,
          interviewScore: this.completeForm.interviewScore,
          interviewResult: this.completeForm.interviewResult,
          interviewFeedback: this.completeForm.interviewFeedback
        }
        completeInterview(data).then(() => {
          this.$modal.msgSuccess('提交成功')
          this.completeOpen = false
          this.getList()
        })
      })
    },
    loadReminders() {
      getAppointmentsForReminder(2).then(res => {
        this.$modal.msgSuccess(`待提醒 ${res.data?.length || 0} 条`)
      })
    },
    handleRemind(row) {
      sendAppointmentReminder(row.appointmentId).then(() => {
        this.$modal.msgSuccess('提醒已发送')
      })
    }
  }
}
</script>

<style scoped>
.appointment-management { padding: 20px; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.page-header h2 { margin: 0; color: #303133; }
.header-actions { display: flex; gap: 10px; }
</style>
